package com.v5.ik;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private String mState;
    private IWXAPI mWXAPI;
    private LikeWechatDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mWXAPI = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
        mWXAPI.registerApp(Constants.APP_ID);
        EventBus.getDefault().register(this);

        findViewById(R.id.wxlogin_btn).setOnClickListener(this);
        findViewById(R.id.phone_login_btn).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.wxlogin_btn) {
            if (!mWXAPI.isWXAppInstalled()) {
                showToast("请先安装微信");
                return;
            }
            dialog = new LikeWechatDialog(this, "请稍等...");
            dialog.show();
            wxLogin();
        } else {
            Intent intent = new Intent();
            Bundle extras = new Bundle();
            extras.putString("page", "login");
            intent.putExtras(extras);
            setResult(RESULT_OK, intent);
            finish();
        }
        v.setEnabled(false);
    }

    private void wxLogin() {
        final SendAuth.Req req = new SendAuth.Req();
        mState = Utils.createRandom(true, 6);
        req.scope = "snsapi_userinfo";
        req.state = mState;
        mWXAPI.sendReq(req);
    }

    @Override
    protected void onDestroy() {
        Log.i("qwe", "onDestroy: Login");
        if (dialog != null && dialog.isShowing())
            dialog.dismiss();

        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(BaseResp baseResp) {
        finish();
    }
}
